package com.chenjt.jvm.first.two_classLoader;

/**
 * 注释：自定义用户类加载器
 *
 * @author chenjt
 * @date 2025/6/4 14:13
 */
public class CustomClassLoader extends ClassLoader{

    /**
     *
     * @param name  字节码文件的路径
     *         The <a href="#name">binary name</a> of the class
     *
     * @return
     * @throws ClassNotFoundException
     */
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {

        try {
            byte[] result = getClassFromCustomPath(name);
            if (result == null) {
                throw new ClassNotFoundException();
            } else {
                return defineClass(name, result, 0, result.length);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        throw new ClassNotFoundException();
    }


    private byte[] getClassFromCustomPath(String name){
        // 从自定义路径中加载指定类：细节略
        // 如果指定路径的字节码文件进行了加密，则需要在此方法中进行解密操作

        return null;
    }


    public static void main(String[] args) throws Exception {

        CustomClassLoader customClassLoader = new CustomClassLoader();

        try {
            Class<?> clazz = Class.forName("One", true, customClassLoader);
            Object obj = clazz.newInstance();
            System.out.println(obj.getClass().getClassLoader());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


}
